package com.sangeng.controller;

import com.sangeng.constant.FileConstants;
import com.sangeng.constant.enums.AppHttpCodeEnum;
import com.sangeng.domain.core.ResponseResult;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@RestController
public class FileOperationController {
    @Autowired
    private FileStorageService fileStorageService;//注入实列

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public ResponseResult uploadFile(MultipartFile img) throws Exception {
        try {
            // 上传文件不能为空
            if (img.isEmpty()) {
                return ResponseResult.errorResult(AppHttpCodeEnum.CONTENT_NOT_NULL);
            }
            // 判断文件大小和类型
            if (img.getSize() > FileConstants.MAX_FILE_SIZE) {
                return ResponseResult.errorResult(AppHttpCodeEnum.FILE_TOO_LARGE);
            }
            // 判断文件是否为图片
            String contentType = img.getContentType();
            if (!contentType.startsWith("image")) {
                return ResponseResult.errorResult(AppHttpCodeEnum.FILE_TYPE_ERROR);
            }
            // 指定oss保存文件路径
            String objectName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/";
            // 上传图片，成功返回文件信息
            FileInfo fileInfo = fileStorageService.of(img).setPath(objectName).upload();
            // 设置返回结果
            return ResponseResult.okResult(fileInfo.getUrl());
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FILE_UPLOAD_ERROR);
        }
    }
}
